package org.dflish.mybatis.encrypt.plugins;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.dflish.mybatis.encrypt.properties.EnCryptProperties;
import org.dflish.mybatis.encrypt.rewrite.EncryptPreParameterRewriter;

import java.sql.Statement;
import java.util.List;

/**
 * @author liangwx
 */
@Slf4j
@Intercepts({
        @Signature(type = StatementHandler.class, method = "parameterize", args = Statement.class)
})
public class EnCryptInterceptor implements Interceptor {

    private final EncryptPreParameterRewriter rewriter;

    public EnCryptInterceptor(EnCryptProperties properties) {
        this.rewriter = new EncryptPreParameterRewriter(properties);
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object target = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(target);
        MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

        String sql = (String) metaObject.getValue("delegate.boundSql.sql");
        List<ParameterMapping> parameterMappings = (List<ParameterMapping>) metaObject.getValue("delegate.boundSql.parameterMappings");
        Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");

        rewriter.rewrite(sql, parameterMappings, parameterObject);

        final Object returnObj = invocation.proceed();

        return returnObj;
    }
}
